<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert
        :closable="false"
        title="添加商品信息"
        type="info"
        center
        show-icon>
      </el-alert>
      <el-steps :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tabs标签页 -->
      <el-form  :model="addGoodsForm" :rules="rules" label-position="top" ref="addGoodsFormRef">
        <el-tabs tab-position="left" v-model="activeIndex" :before-leave="tabs" @tab-click="tabClick">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addGoodsForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type="number" v-model="addGoodsForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input type="number" v-model="addGoodsForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_number">
              <el-cascader
              v-model="addGoodsForm.goods_cat"
              :options="goodsCate"
              :props="cascaderProps"
              @change="cascaderHandleChange">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" name="1" v-for="item in manyData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="item" v-for="(item, index) in item.attr_vals" :key="index" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
           <el-form-item :label="item.attr_name" name="1" v-for="item in onlyData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action: 上传的接口地址 -->
            <!-- :on-preview：点击进行预览触发 -->
            <!-- :on-remove：点击移除图片触发 -->
            <!-- :on-success：上传图片成功后 -->
            <el-upload
              action="http://liufusong.top:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="uploadSuccess"
              :headers="uploadHeaders"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addGoodsForm.goods_introduce"></quill-editor>
            <el-button type="primary" style="margin-top: 20px;" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览对话框 -->
    <el-dialog
      title="预览图片"
      :visible.sync="previewDialogVisible"
      width="50%">
      <img :src="imgUrl" style="width: 100%">
    </el-dialog>
  </div>
</template>

<script>
import { cloneDeep } from 'lodash'
export default {
  data () {
    return {
      activeIndex: 0,
      addGoodsForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 商品分类id
        goods_cat: [],
        pics: [
        // 图片上传成功后服务器的图片地址
        ],
        goods_introduce: '',
        attrs: []

      },
      rules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ]
      },
      goodsCate: [],
      cascaderProps: {
        expandTrigger: 'hover',
        // label 显示字段
        label: 'cat_name',
        value: 'cat_id'
      },
      manyData: [],
      onlyData: [],
      uploadHeaders: {
        Authorization: sessionStorage.getItem('token')
      },
      previewDialogVisible: false,
      imgUrl: ''
    }
  },
  computed: {
    // 三级分类id
    cateId () {
      if (this.addGoodsForm.goods_cat.length !== 3) {
        return null
      }
      return this.addGoodsForm.goods_cat[2]
    }
  },
  created () {
    this.getGoodsCate()
  },

  methods: {
    // 获取商品分类
    async getGoodsCate () {
      const { data: res } = await this.$axios.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.goodsCate = res.data
    },
    // 选择了级联选择器
    cascaderHandleChange () {
      if (this.addGoodsForm.goods_cat.length !== 3) {
        this.addGoodsForm.goods_cat = []
      }
    },
    // 在离开某一项tabs标签页的时候触发
    tabs (activeName, oldName) {
      if (oldName === '0' && this.addGoodsForm.goods_cat.length !== 3) {
        this.$message.error('选择三级分类')
        return false
      }
    },
    // 获取商品参数
    async getGoodsParams (sel) {
      const { data: res } = await this.$axios.get('categories/' + this.cateId + '/attributes', {
        params: {
          sel: sel
        }
      })
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      if (sel === 'many') {
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(',')
        })
        this.manyData = res.data
      } else {
        this.onlyData = res.data
      }
    },
    // 点击了某一项tabs标签页
    tabClick () {
      if (this.activeIndex === '1') {
        this.getGoodsParams('many')
      } else if (this.activeIndex === '2') {
        this.getGoodsParams('only')
      }
    },
    handlePreview (file) {
      console.log(file)
      this.previewDialogVisible = true
      this.imgUrl = 'http://liufusong.top:8888/' + file.response.data.tmp_path
    },
    handleRemove (file) {
      const index = this.addGoodsForm.pics.findIndex(item => {
        return item.pic === file.response.data.tmp_path
      })
      console.log(index)
      this.addGoodsForm.pics.splice(index, 1)
    },
    uploadSuccess (res) {
      console.log('上传成功', res)
      this.addGoodsForm.pics.push({
        pic: res.data.tmp_path
      })
    },
    addGoods () {
      this.$refs.addGoodsFormRef.validate(async flag => {
        if (!flag) return this.$message.error('完善基本信息必填项')
        // 两份表单数据
        // 一份用来渲染数据，一份给后台
        // 深拷贝第一种方式
        // const form = JSON.parse(JSON.stringify(this.addGoodsForm))
        // 深拷贝第二种方式
        const form = cloneDeep(this.addGoodsForm)
        form.goods_cat = form.goods_cat.join(',')
        this.manyData.forEach(item => {
          form.attrs.push({ attr_id: item.attr_id, attr_value: item.attr_vals.join(',') })
        })
        this.onlyData.forEach(item => {
          form.attrs.push({ attr_id: item.attr_id, attr_value: item.attr_vals })
        })
        console.log(form, this.addGoodsForm)
        // 深拷贝第三种方式：递归拷贝(递归循环)
        const { data: res } = await this.$axios.post('goods', form)
        // console.log(res)
        if (res.meta.status !== 201) return this.$message.error('创建失败')
        this.$message.success('创建成功')
        this.$router.push('/goods')
      })
    }
  }
}
</script>

<style scoped lang='less'>
.el-steps {
  margin: 20px auto;
}
// /deep/穿透到组件内部,给内部的结构加样式
/deep/.el-step__title {
  font-size:12px;
}
.el-checkbox {
  margin-right: 0;
}
/deep/.ql-editor {
  height: 400px;
}
</style>
